<!DOCTYPE html>
<html style="height: 100%;">

<head>
    <title>信息科开放平台</title>
    <link rel="shortcut icon" href="/static/img/Icon.ico"> <!-- 网站图标 必须ico文件 -->

    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
    <script src="/static/js/jquery-3.4.1.min.js"></script>

    <!--引入WebSocket断线重连插件-->
    <script src="/static/js/reconnecting-websocket.min.js"></script>

    <!-- 引入CSS： elementUI -->
    <link rel="stylesheet" href="/static/element-UI/index.css">
    <!-- 引入JS： Vue (before ElementUI JS)-->
    <script src="/static/vue/vue.js"></script>
    <!-- 引入JS： ElementUI JS -->
    <script src="/static/element-UI/index.js"></script>


    <style>
        body{
            /* 鼠标指针的样式 */
            cursor: url(/static/img/cursor.ico),auto;
        }
        .SFZform {
            border: 1px solid #DCDFE6;
            border-radius: 20px;
            padding: 20px;
            margin: 30px auto;
            box-shadow: 0 0 30px #DCDFE6;
            background-color: white;
        }
    </style>
    <script>
        // 低版本谷歌不支持ES6，没有padStart函数，解决办法是自己重新实现String.prototype.padStart
        // 需在head中定义
        if (!String.prototype.padStart) {
            String.prototype.padStart = function padStart(targetLength, padString) {
                targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
                padString = String((typeof padString !== 'undefined' ? padString : ' '));
                if (this.length > targetLength) {
                    return String(this);
                } else {
                    targetLength = targetLength - this.length;
                    if (targetLength > padString.length) {
                        padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
                    }
                    return padString.slice(0, targetLength) + String(this);
                }
            };
        }
    </script>
</head>


<body style="height: 100%;overflow:hidden;margin: 0px;">
<div id="app" style="height: 100%;">

    <!--    顶栏  -->
    <el-row>
        <el-menu
                :default-active="activeIndex_top"
                class="el-menu-demo"
                mode="horizontal"
                @select="topMenu_handleSelect"
                background-color="#545c64"
                text-color="#fff"
                active-text-color="#ffd04b">
            <el-menu-item index="1">疫苗接种叫号系统</el-menu-item>

            <el-submenu index="2" style="float: right">
                <template slot="title" id="userNameText">信息科 陈呵呵</template>
                <el-menu-item index="2-1">个人资料</el-menu-item>
                <el-menu-item index="2-2">注销</el-menu-item>
            </el-submenu>

        </el-menu>
    </el-row>


    <el-row style="height: 100%;background-image: url(/static/img/background.jpg);background-repeat:no-repeat;background-size:100% 100%;">
        <!--    左侧菜单    -->
        <el-col :span="3" style="height: 100%">
            <el-menu
                    default-active="2"
                    class="el-menu-vertical-demo"
                    @open="leftMenu_handleOpen"
                    @close="leftMenu_handleClose"
                    @select="leftMenu_handleSelect"
                    background-color="#545c64"
                    text-color="#fff"
                    active-text-color="#ffd04b"
                    style="height: 100%">
                <el-menu-item index="1">
                    <i class="el-icon-menu"></i>
                    <span slot="title">叫号</span>
                </el-menu-item>
                <el-menu-item index="2">
                    <i class="el-icon-menu"></i>
                    <span slot="title">身份证取号</span>
                </el-menu-item>
                <el-menu-item index="3">
                    <i class="el-icon-document"></i>
                    <span slot="title">统计报表</span>
                </el-menu-item>

            </el-menu>
        </el-col>

        <!--     右侧工作区域    -->
        <el-col :span="20" :offset="1" style="height:100%;">

            <!--空白间隔栏-->
            <el-row style="height: 15px;"></el-row>

            <!-- 身份证表单 -->
            <el-row>
                <el-col :span="16" :offset="1" class="SFZform">
                    <el-row>
                        <el-col :span="14" :offset="10" style="height:100%;">
                            <el-form label-position="right" label-width="100px"
                                     style="background-color: white"
                            >
                                <el-form-item>
                                    <el-button id="btn_readCard" type="warning" @click="readCard()"
                                               :loading="isLoading_btn_readCard">
                                        读身份证
                                    </el-button>

                                    <el-button id="btn_takeQueueNumber" type="warning" @click="takeQueueNumber()"
                                               :loading="isLoading_btn_takeQueueNumber">取号
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="10">

                            <el-form label-position="right" label-width="100px"
                                     style="background-color: white"
                            >
                                <el-form-item id="imgItem">
                                    <template>
                                        <div class="demo-fit">
                                            <div class="block">
                                                <el-avatar style="background-color:white" id="img" shape="square"
                                                           :size="180" fit="fill" src="/static/img/SFZ head.jpg"></el-avatar>
                                            </div>
                                        </div>
                                    </template>

                                </el-form-item>
                            </el-form>
                        </el-col>
                        <el-col :span="14">
                            <el-form label-position="right" label-width="100px" :model="SFZdata"
                                     :rules="rules"
                                     style="background-color: white"
                            >
                                <el-form-item label="姓名：" prop="name">
                                    <el-input v-model="SFZdata.name" id="nameInput"></el-input>
                                </el-form-item>
                                <el-form-item label="身份证号：" prop="sfzh">
                                    <el-input v-model="SFZdata.sfzh"></el-input>
                                </el-form-item>
<!--                                <el-form-item label="出生年月：">-->
<!--                                    <el-input v-model="SFZdata.csny"></el-input>-->
<!--                                </el-form-item>                               -->
                                <el-form-item label="年龄：">
                                    <el-input v-model="SFZdata.age"></el-input>
                                </el-form-item>
                                <el-form-item label="性别：">
                                    <el-input v-model="SFZdata.gender"></el-input>
                                </el-form-item>

                                <el-form-item label="住址：">
                                    <el-input v-model="SFZdata.address"></el-input>
                                </el-form-item>
                                <el-form-item label="备注：">
                                    <el-input v-model="SFZdata.bzxx"></el-input>
                                </el-form-item>
                            </el-form>
                        </el-col>

                    </el-row>


                </el-col>
            </el-row>


        </el-col>
    </el-row>
</div>


<script>
    /*
    *  定义全局变量
    */
    var g_toastHandle;  // vue创建的toast实例，用于提示取号成功的病人信息
    var IpAndPort = window.location.host; // IP和端口号

    // 解析token
    var token = getCookie('token');
    var strings = token.split("."); //截取token，获取载体
    var userInfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/"))))); //解析，需要吧‘_’,'-'进行转换否则会无法解析
    $("#userNameText")[0].innerHTML = "&nbsp;[&nbsp;" + userInfo.ksmc + "&nbsp;]&nbsp;&nbsp;" + userInfo.ygxm;


    // 本页面的vue对象
    var vue = new Vue({
        el: '#app',
        data() {
            return {
                activeIndex_top: '1',
                SFZdata: {
                    name: '',
                    sfzh: '',
                    address: '',
                    gender: '',
                    csny: '',
                    age:'',
                    bzxx:''
                },
                rules: {
                    name: [
                        {required: true, message: '姓名是必填项', trigger: 'blur'}
                    ]
                    , sfzh: [
                        {required: true, message: '身份证号是必填项', trigger: 'blur'}
                    ]
                },
                isLoading_btn_readCard: false,          // 读卡按钮的'loading'样式
                isLoading_btn_takeQueueNumber: false    // 取号按钮的'loading'样式
            };
        },
        methods: {
            //
            // 点击【菜单栏】
            //
            topMenu_handleSelect(key, keyPath) {
                console.log(key, keyPath);
                if(key=='2-2'){
                    document.cookie = "token=;path=/";  // token置空
                    window.location.href = "http://" + IpAndPort + "/ViewController/Login";
                }
            },
            leftMenu_handleOpen(key, keyPath) {
                console.log(key, keyPath);
            },
            leftMenu_handleClose(key, keyPath) {
                console.log(key, keyPath);
            },
            leftMenu_handleSelect(key, keyPath) {
                console.log(key, keyPath);
                if (key == '1') {
                    window.location.href = "http://" + IpAndPort + "/ViewController/YM_CallNumber";
                } else if (key == '2') {
                    //window.location.href = "http://" + IpAndPort + "/ViewController/YM_TakeNumber";
                }
                else  if(key=='3'){
                    window.location.href = "http://" + IpAndPort + "/ViewController/YM_Statistic";
                }
            }

            // 读卡
            , readCard() {
                $("#btn_readCard").blur();  // 按钮颜色恢复
                vue.isLoading_btn_readCard = true; // 按钮loading样式

                // 一旦点击读卡，就隐藏上一次的toast取号成功提示
                if (g_toastHandle != undefined) {
                    g_toastHandle.close();
                }


                var ws = new WebSocket("ws://127.0.0.1:9998");

                //当WebSocket创建成功时，触发onopen事件
                ws.onopen = function () {
                    console.log("进入onopen事件");

                    // 消息发送到服务端
                    console.log("ReadSFZ");
                    ws.send("ReadSFZ");

                };

                //当收到服务端发来的消息时，触发onmessage事件
                ws.onmessage = function (e) {
                    // console.log("接收到消息：" + e.data);

                    var jsonObj = $.parseJSON(e.data);
                    if (jsonObj.status == true) {
                        if (jsonObj.detail.photo != undefined) {
                            document.getElementById('img').children[0].src = 'data:image/bmp;base64,' + jsonObj.detail.photo;   //照片加载（服务端以base64编码照片文件，以字符串形式发送）
                            jsonObj.detail.photo = '';
                        }
                        vue.SFZdata = jsonObj.detail;

                        // 根据身份证号获取年龄
                        jQuery(function ($) {
                            vue.SFZdata.age = GetAge(vue.SFZdata.sfzh);
                        });

                    } else if (jsonObj.status == false) {
                        vue.$message.error('读卡失败：' + jsonObj.detail);
                    }
                    vue.isLoading_btn_readCard = false; // 按钮loading样式
                    // 关闭webSocket
                    console.log("尝试断开WebSocket连接" + e.data);
                    ws.close();
                };
                ws.onerror = function (e) {
                    vue.$message.error('读卡失败：不能连接到ChyReadCard服务');
                    console.log("读卡失败：不能连接到ChyReadCard服务" + e.data);
                    vue.isLoading_btn_readCard = false; // 按钮loading样式
                };
                ws.onclose = function (e) {
                    console.log("WebSocket连接已关闭");
                    vue.isLoading_btn_readCard = false; // 按钮loading样式
                };

            }

            // 取号
            , takeQueueNumber() {
                $("#btn_takeQueueNumber").blur();  // 按钮颜色恢复

                // 合法性验证
                if (this.SFZdata.name == '') {
                    vue.$message.warning('请填写姓名');
                    return;
                } else if (this.SFZdata.sfzh == '') {
                    vue.$message.warning('请填写身份证号');
                    return;
                }

                // 点击取号后，按钮禁用1秒
                vue.isLoading_btn_takeQueueNumber = true; // 按钮loading样式
                var timeoutObj = setTimeout(function () {
                    vue.isLoading_btn_takeQueueNumber = false; // 按钮loading样式
                    // 清除已设置的setTimeout对象
                    clearTimeout(timeoutObj)
                }, 1 * 1000); // 1秒


                /* 传递MAP */
                var map = new Map();
                map.set("ywlx", 2);               // 暂时写死
                map.set("brxm", this.SFZdata.name);
                map.set("sfzh", this.SFZdata.sfzh);
                map.set("brnl", this.SFZdata.age);
                map.set("brxb", this.SFZdata.gender);
                map.set("jtdz", this.SFZdata.address);
                map.set("bzxx", this.SFZdata.bzxx);
                map.set("dlxh", 2);
                map.set("dlmc", '疫苗接种队列');

                //map转obj
                var obj = Object.create(null);
                for (var key of map) {
                    obj[key[0]] = key[1];
                }
                $.ajax({
                    url: "http://" + IpAndPort + "/AppointController/takeQueueNumber",
                    type: "POST",
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify(obj),
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (data) {
                        var jsonObj = $.parseJSON(data);
                        if (jsonObj.status == false) {
                            vue.$message.error('取号失败：' + jsonObj.detail);
                            vue.isLoading_btn_takeQueueNumber = false;
                        } else if (jsonObj.status == true) {


                            // 接收号码信息
                            var pdxx = $.parseJSON(jsonObj.detail);
                            var pdhm = pdxx.pdhm;
                            var brxm = pdxx.brxm;
                            var sfzh = pdxx.sfzh;
                            var yysj = pdxx.yysj;

                            // 打印小票
                            var info = "title=疫苗接种&count=1";
                            info += ("["
                                + "brxm=" + brxm
                                + "&pdhm=" + pdhm
                                + "&sfzh=" + sfzh
                                + "&qhsj=" + dateFormat("YYYY-mm-dd HH:MM:SS", new Date(yysj))
                                + "&]")
                            var ws = new WebSocket("ws://127.0.0.1:9999");   // 通过webSocket与本地打印机通信
                            ws.onopen = function () {
                                ws.send(info);
                                ws.close();
                            }


                            // 关闭上一次的toast提示
                            if (g_toastHandle != undefined) {
                                g_toastHandle.close();
                            }

                            // message展示取号成功的信息
                            g_toastHandle = vue.$message.success({
                                dangerouslyUseHTMLString: true, // 使组件能够解析换行标签
                                message: '取号成功：&ensp;&ensp;' + pdhm + '号&ensp;&ensp;&ensp;' + brxm,
                                duration: 0, // 不自动关闭
                                showClose: true
                            });

                            // toast展示取号成功的信息
                            // const h = vue.$createElement;
                            // g_toastHandle = vue.$notify({
                            //     title: '取号成功',
                            //     message: h('b', {style: 'color: #ebb563;font-size:16px'},  + pdhm + '号 ' + brxm),
                            //     offset: 70, // 偏移70位置
                            //     duration: 0 // 不自动关闭
                            // });

                            // 表单置空
                            vue.SFZdata.name = '';
                            vue.SFZdata.sfzh = '';
                            vue.SFZdata.csny = '';
                            vue.SFZdata.address = '';
                            vue.SFZdata.gender = '';
                            vue.SFZdata.age = '';
                            vue.SFZdata.bzxx = '';
                            document.getElementById('img').children[0].src = '/static/img/SFZ head.jpg';
                        }
                    },
                    error: function (data) {
                        vue.$message.error('取号失败：连接服务端时发生错误');
                        vue.isLoading_btn_takeQueueNumber = false;
                    }
                });
            }

        }
    });

    // 处理：照片元素的margin
    $($("#imgItem")[0].childNodes[1]).css("margin-left","50px")


    /*
    * JS工具方法
    * */

    /**
     * 获取指定名称的cookie
     */
    function getCookie(name) {
        var strcookie = document.cookie;//获取cookie字符串
        var arrcookie = strcookie.split("; ");//分割
        //遍历匹配
        for (var i = 0; i < arrcookie.length; i++) {
            var arr = arrcookie[i].split("=");
            if (arr[0] == name) {
                return arr[1];
            }
        }
        return "";
    }

    /**
     * 时间日期格式化
     *
     */
    function dateFormat(fmt, date) {
        var ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (var k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
            ;
        }
        ;
        return fmt;
    }

    //鼠标点击弹出爱心❤
    jQuery(function($){
        showLoveWhenMouseClick(window, document);
    });
</script>

</body>
<!-- 在body之后加载鼠标点击特效的JS（鼠标点击放烟花、弹出爱心❤） -->
<script src="/static/js/mouse-click.js"></script>

<!-- 引入工具库 -->
<script src="/static/js/MyUtils.js"></script>


</html>